package celiasoft.itasalib.query.resultparser;

import java.util.ArrayList;
import java.util.List;

import org.htmlcleaner.TagNode;
import org.w3c.dom.Document;

import celiasoft.itasalib.query.ResultsMetaInfo;
import celiasoft.itasalib.structures.DataElement;
import celiasoft.itasalib.structures.TranslationStatusEntry;

public class QueryTranslationsStatusResultParser extends IQueryResultParser {

	@SuppressWarnings("unused")
	private static final String TAG = "itasalib.parser.QueryTranslationsStatusResultParser";

	public List<DataElement> parse(Document doc, ResultsMetaInfo meta) {
		return null;
	}

	@Override
	public List<DataElement> parse(TagNode root, ResultsMetaInfo meta) {

		ArrayList<DataElement> res = new ArrayList<DataElement>();

		TagNode actualRoot = HTMLParsingHandler.getElementByClass(root,
				"table", "barremod");
		
		if (actualRoot != null) {
			actualRoot = actualRoot.getElementsByName("tbody", false)[0]; //!
			
			TagNode elements[] = actualRoot.getElementsByName("tr", false);
			
			if (elements.length < 1) {
				return res;
			}

			for (int i = 0; i < elements.length; i++) {
				TagNode n = elements[i];
				
				DataElement el = parseTranslationStatusEntry(n);
				if (el != null) {
					res.add(el);
				}
			}
		}

		if (res.size() > 0) {
			setMetaData(null, meta);
		}

		return res;
	}

	private DataElement parseTranslationStatusEntry(TagNode n) {
	
		TranslationStatusEntry entry = null;
		
		TagNode[] h2s =  n.getElementsByName("h2", true);
		
		if (h2s.length < 1) {
			return  entry;
		}
		
		StringBuffer textBuff = h2s[0].getText();
		if(textBuff == null){
			return  entry;
		}
		entry = new TranslationStatusEntry(textBuff.toString());
		TagNode div = HTMLParsingHandler.getElementByClass(n, "div", "style2");
		if(div != null){
			entry.setStatus(div.getText().toString());
		}else{
			div = HTMLParsingHandler.getElementByClass(n, "div", "style1");
			if(div != null){
				entry.setStatus(div.getText().toString());
			}
		}
	
		return entry;
	}
}
